package com.pwrd.sframe.conn;

import com.google.common.base.Optional;
import com.pwrd.sframe.core.CallInfo;
import com.pwrd.sframe.core.Service;
import com.pwrd.sframe.support.exception.SysException;
import com.pwrd.sframe.core.Port;
import com.pwrd.sframe.support.constant.ConstNode;
import io.netty.channel.Channel;

import java.util.LinkedList;

/**
 * @Auther syc.
 * @Date 2017/1/9 11:02.
 */
public class Connection extends Service {

    //当前连接通道
    private Channel channel;

    //连接Id
    private Optional<Integer> connIdOp;

    // 连接状态信息
    private ConnectionInfo info;

    CallInfo gateInfo = new CallInfo(ConstNode.NODE_DEFAULT, ConstNode.PORT_DEFAULT, ConstNode.SERVICE_GATE);

    //    private final ConcurrentLinkedQueue<byte[]> recvMsgQ = new ConcurrentLinkedQueue<>(); //CAS算法
    private final LinkedList<byte[]> recvMsgQ = new LinkedList<>();

    public void recvHandler(byte[] bytes) {
        try {
            recvMsgQ.add(bytes);
        } catch (Exception e) {
            throw new SysException(e);
        }
    }


    public Connection(Channel channel, Port port, Integer connId) {

        super(port);
        this.channel = channel;
        this.connIdOp = Optional.of(connId);
        info = new ConnectionInfo(port, connId);
    }

    /**
     * 处理接收到的信息
     */
    public void pulseRecv() {
        while (!recvMsgQ.isEmpty()) {
            byte[] msgByte = recvMsgQ.poll();
            dispatch(msgByte);
        }
    }

    public void dispatch(byte[] msgByte) {
        switch (info.status) {
            case LOGIN:
                port.call(gateInfo, "GateService::login", new Object[] {null, connIdOp.get(), msgByte});

        }
    }

    @Override
    public void pulseOverride() {
        pulseRecv();
    }

    @Override
    public Object getKey() {
        return connIdOp.get();
    }
}
